package com.yxhl.zoume.core.officialcar.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.common.ui.activity.base.BaseActivityWithToolBar;
import com.yxhl.zoume.core.specialcar.model.OperationForToolbar;
import com.yxhl.zoume.core.specialcar.model.DialTelephoneEvent;
import com.yxhl.zoume.core.car.fragment.common.CancelCarOrderFeedbackFragment;
import com.yxhl.zoume.core.officialcar.fragment.OfficialCarScheduleMapFragment;
import com.yxhl.zoume.data.rxbus.RxBus;
import com.yxhl.zoume.di.component.car.DaggerOfficialCarComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.DeviceUtils;
import com.yxhl.zoume.utils.DiskCacheUtils;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;
import com.yxhl.zoume.utils.permission.PermissionHelper;

import java.util.List;

import butterknife.BindView;

/**
 * created by sugarya
 * 公务车下单
 */
public class OfficialCarScheduleActivity extends BaseActivityWithToolBar {

    public static final String FRAGMENT_CANCEL_CAR_ORDER_FEEDBACK = "CancelCarOrderFeedbackFragment";
    public static final String FRAGMENT_OFFICIAL_CAR_SCHEDULE_MAP = "OfficialCarScheduleMapFragment";
    public static final String FRAGMENT_COMMENT_ON_DRIVER = "CommentOnDriverFragment";
    private static final String TAG = "SpecialCarScheduleAct";
    @BindView(R.id.frame_official_car_service_body)
    FrameLayout mServiceBodyFrame;


    //arguments
    private String mOrderId;

    private String mCurrentShowFragmentTab;
    private MaterialDialog mMaterialDialog;

    public static Intent getCallingIntent(Activity activity, String carOrderId) {
        Intent launch = new Intent(activity, OfficialCarScheduleActivity.class);
        launch.putExtra(UIConstants.Car.INTENT_KEY_OFFICIAL_ORDER_SERVICE_ORDER_ID, carOrderId);
        return launch;
    }

    /**
     * 推送专用
     *
     * @param context
     * @param carOrderId
     * @return
     */
    public static Intent getPushIntent(Context context, String carOrderId) {
        Intent launch = new Intent(context, OfficialCarScheduleActivity.class);
        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        launch.putExtra(UIConstants.Car.INTENT_KEY_OFFICIAL_ORDER_SERVICE_ORDER_ID, carOrderId);
        return launch;
    }

    private void onRxBusEvent() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleIntent();
        onRxBusEvent();
        initializeShow();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent();
        initializeShow();
    }

    private void handleIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mOrderId = intent.getStringExtra(UIConstants.Car.INTENT_KEY_OFFICIAL_ORDER_SERVICE_ORDER_ID);
            LOG.e(TAG, "OfficialCarScheduleAct mOrderId=" + mOrderId);
            DiskCacheUtils.getInstance(mBaseContext).saveOfficialCarOrderId(mOrderId);
        }
    }


    private void initializeShow() {
        displayOneFragment(FRAGMENT_OFFICIAL_CAR_SCHEDULE_MAP);
    }


    /**
     * 显示特定Tag的Fragment,如果是第一次显示,则新建并添加该Fragment
     *
     * @param fragmentTab
     */
    public void displayOneFragment(String fragmentTab) {
        mCurrentShowFragmentTab = fragmentTab;

        FragmentManager manager = getSupportFragmentManager();
        if (manager != null) {
            FragmentTransaction transaction = manager.beginTransaction();

            //设置过渡动画
            transaction.setCustomAnimations(R.anim.right_enter, R.anim.left_out, 0, 0);

            List<Fragment> fragments = manager.getFragments();
            if (fragments != null && fragments.size() > 0) {
                for (Fragment f : fragments) {
                    if (f != null) {
                        transaction.hide(f);
                    }
                }
            }

            Fragment fragmentByTag = manager.findFragmentByTag(fragmentTab);
            if (fragmentByTag != null) {
                transaction.show(fragmentByTag);
            } else {
                transaction.add(R.id.frame_official_car_service_body, fragmentProvider(fragmentTab), fragmentTab);
            }

            transaction.commitAllowingStateLoss();
        }
    }

    public void displayOneFragment(String fragmentTab, Fragment needfragment) {
        mCurrentShowFragmentTab = fragmentTab;

        FragmentManager manager = getSupportFragmentManager();
        if (manager != null) {
            FragmentTransaction transaction = manager.beginTransaction();

            //设置过渡动画
            transaction.setCustomAnimations(R.anim.right_enter, R.anim.left_out, 0, 0);

            List<Fragment> fragments = manager.getFragments();
            if (fragments != null && fragments.size() > 0) {
                for (Fragment f : fragments) {
                    if (f != null) {
                        transaction.hide(f);
                    }
                }
            }

            Fragment fragmentByTag = manager.findFragmentByTag(fragmentTab);
            if (fragmentByTag != null) {
                transaction.show(fragmentByTag);
            } else {
                transaction.add(R.id.frame_official_car_service_body, needfragment, fragmentTab);
            }

            transaction.commitAllowingStateLoss();
        }
    }

    private Fragment fragmentProvider(String fragmentTag) {
        Fragment fragment;
        switch (fragmentTag) {
            case FRAGMENT_CANCEL_CAR_ORDER_FEEDBACK:
                fragment = CancelCarOrderFeedbackFragment.newInstance(mOrderId);
                break;
            case FRAGMENT_OFFICIAL_CAR_SCHEDULE_MAP:
                fragment = OfficialCarScheduleMapFragment.newInstance(mOrderId);
                break;
            default:
                fragment = OfficialCarScheduleMapFragment.newInstance(mOrderId);
        }
        return fragment;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //打电话给司机
            case PermissionHelper.REQUEST_CODE_CALL_SPECIAL_CAR_DRIVER:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    RxBus.getInstance().send(new DialTelephoneEvent(DialTelephoneEvent.FROM_SCHEDULE_DRIVER_MOBILE));
                } else {
                    PromptUtils.showShort(this, getString(R.string.special_car_schedule_deny_hint));
                }
                break;
            //打电话给客服
            case PermissionHelper.REQUEST_CODE_CALL_CUSTOMER_SERVICE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    DeviceUtils.dialTelPhone(this, getString(R.string.service_mobile));
                } else {
                    PromptUtils.showShort(this, getString(R.string.special_car_schedule_deny_hint));
                }
                break;
        }
    }


    @Override
    public void onBackPressed() {
        switch (mCurrentShowFragmentTab) {
            case FRAGMENT_CANCEL_CAR_ORDER_FEEDBACK:
                displayOneFragment(FRAGMENT_OFFICIAL_CAR_SCHEDULE_MAP);
                break;
            case FRAGMENT_COMMENT_ON_DRIVER:
                displayOneFragment(FRAGMENT_OFFICIAL_CAR_SCHEDULE_MAP);
                break;
            default:
                super.onBackPressed();
                overridePendingTransition(R.anim.right_enter, R.anim.noanimation);
        }
    }


    @Override
    protected void onHeaderLeftClick(View view) {
        onBackPressed();
    }

    @Override
    protected void onHeaderRightClick(View view) {
        if (view instanceof TextView) {
            TextView rightTv = (TextView) view;
            String operationStr = rightTv.getText().toString().trim();
            switch (operationStr) {
                case OperationForToolbar.CANCEL_TRIP:
//                    mMaterialDialog = DialogUtils.getDialog(
//                            this,
//                            getString(R.string.special_car_dialog_cancel_schedule_message),
//                            getString(R.string.special_car_dialog_confirm),
//                            getString(R.string.special_car_dialog_cancel),
//                            new MaterialDialog.SingleButtonCallback() {
//                                @Override
//                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    displayOneFragment(FRAGMENT_CANCEL_CAR_ORDER_FEEDBACK);
//                                }
//                            },
//                            new MaterialDialog.SingleButtonCallback() {
//                                @Override
//                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                                    dialog.dismiss();
//                                }
//                            }
//                    );
//                    mMaterialDialog.show();
                    break;

                case OperationForToolbar.CUSTOMER_SERVICE:
                    if (PermissionHelper.checkPhonePermission(this)) {
                        DeviceUtils.dialTelPhone(this, getString(R.string.service_mobile));
                    } else {
                        PermissionHelper.takeCallPhonePermission(this, PermissionHelper.REQUEST_CODE_CALL_CUSTOMER_SERVICE);
                    }
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mMaterialDialog != null && mMaterialDialog.isShowing()) {
            mMaterialDialog.dismiss();
        }
        super.onDestroy();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_official_car_schedule;
    }

    @Override
    protected void initializeInjector() {
        DaggerOfficialCarComponent
                .builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(this))
                .build()
                .inject(this);
    }


}
